﻿using Emgu.CV;
using Emgu.CV.Structure;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FaceRecognition
{
    public class PgmToPng
    {


        public PgmToPng() { }

        public static int[,] GetPgmFileGrayArray(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                using (BinaryReader reader = new BinaryReader(fs, Encoding.ASCII))
                {
                    if (reader.ReadChar() == 'P' && reader.ReadChar() == '5')
                    {
                        reader.ReadChar();
                        int width = 0;
                        int height = 0;
                        int level = 0;
                        bool two = false;

                        StringBuilder sb = new StringBuilder();

                        width = ReadNumber(reader, sb);
                        height = ReadNumber(reader, sb);
                        level = ReadNumber(reader, sb);

                        int[,] grays = new int[width, height];

                        two = (level > 255);

                        for (int i = 0; i < height; i++)
                        {
                            for (int j = 0; j < width; j++)
                            {
                                byte v;
                                if (two)
                                {
                                    v = (byte)(((double)((reader.ReadByte() << 8) + reader.ReadByte()) / level) * 255.0);
                                }
                                else
                                {
                                    v = (byte)reader.ReadByte();
                                }

                                grays[j, i] = v;

                            }

                        }
                        return grays;
                    }
                    else { return null; }
                }
            }
        }

        private static int ReadNumber(BinaryReader reader, StringBuilder sb)
        {
            char c = '\0';
            sb.Length = 0;
            while (Char.IsDigit(c = reader.ReadChar()))
            {
                sb.Append(c);
            }
            return int.Parse(sb.ToString());
        }
        public static Image<Gray ,byte> GetPng(int[,] gray)
        {
            int w = gray.GetLength(0);
            int h = gray.GetLength(1);
            Image<Gray, byte> png = new Image<Gray, byte>(w, h);
            for(int i=0;i<h;i++)
            {
                for(int j = 0; j < w; j++)
                {
                    png[j, i] = new Gray( gray[i, j]);
                }
            }
            return png;
        }

    }
}
